//= require <framework/events/Observer>

namespace('jswing.models.ComponentModel', {
	"@traits": [new Observer],
	
	preInitialize: function(json) {
		var self = this;
		var args = arguments;
		this.resetListeners();
		this.resetModel(json);
	},
    
	start: function() {},
	
	resetListeners: function() {
		this.observations = [];
		this.subscribers = {};
	},
	
	resetModel: function(json) {
		this.data = json;
	},
	
	set: function(prop, value) {
		this.data[prop] = value;
		this.dispatchEvent("modelchanged", {
			model: this,
			name: prop
		});
	},
	
	get: function(prop) {
		return this.data[prop]; 
    },
	
	isValid: function() {
        var self = this;
        if(this["@schema"]) {
            var schema = this["@schema"];
            var errors = JSONSchema.validate(this.model,schema);
    		if(errors && errors.length) {
				logger.info("The component model of type '" + this.namespace + "' contains an invalid object model:")
    			var logerror = function(err){
    				if (logger) {
						logger.error("'" + err.property + "' " + err.message);
					}
    			};
    			errors.forEach(logerror);
    			return false;
    		}
    		return true;
        }
		return true;
	},
	
	update: function(json, merge) {
		if (typeof json !== "object") {  throw new TypeError("Invalid json type passed to jswing.models.ComponentModel#update(json). Expected an object resembling json/object literal"); }
//		js.merge(this.model, json);
//		this.dispatchEvent("model:updated");
		if(merge && json) {
			js.merge(this.model, json);
		}
		else if(json && !merge) {
			js.extend(this.model, json);
		};
		
		this.dispatchEvent("model:updated");
	},
	
	find: function(jsonquery) {
		return json.JSONQuery(jsonquery, this.model);
	},
	
	registerUI:function(){}
});
